package by.alex.dzeshko.facebooksuperclient;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.support.v4.app.LoaderManager;
import android.support.v4.app.LoaderManager.LoaderCallbacks;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import by.alex.dzeshko.facebooksuperclient.adapter.FeedCursorAdapter;
import by.alex.dzeshko.facebooksuperclient.api.ApiRequest;
import by.alex.dzeshko.facebooksuperclient.constants.FbConstants;
import by.alex.dzeshko.facebooksuperclient.database.DbNewsfeedHelper;
import by.alex.dzeshko.facebooksuperclient.database.DbUsersHelper;
import by.alex.dzeshko.facebooksuperclient.http.RequestBuilder;
import by.alex.dzeshko.facebooksuperclient.image.ImageLoader;
import by.alex.dzeshko.facebooksuperclient.oauth.FBOAuthHelper;
import by.alex.dzeshko.facebooksuperclient.providers.contract.FbContract;
import by.alex.dzeshko.facebooksuperclient.service.FeedService;
import by.alex.dzeshko.facebooksuperclient.service.ProfileService;
import by.alex.dzeshko.facebooksuperclient.utils.InetChecker;
import by.alex.dzeshko.facebooksuperclient.utils.ViewHider;

public class ProfilePageFragment extends ListFragment implements OnScrollListener {

	private static final String LOG_TAG = "ProfilePageFragment";

	private TextView mTextViewName, mTextViewBirthDay, mTextViewLocation;
	
	private ImageView mImageView;
	
	private ListView mListViewProfile;
	
	private ImageButton mButtonAdd, mButtonRefresh;

	private View mViewLoading, mViewProfileInfo, mViewRefreshish;

	private String mNextPageUrl;
	
	private boolean mIsLoading;
	
	private FeedCursorAdapter mProfileFeedAdapter;
	
	private BroadcastReceiver mBroadcastReceiver;
	
	private DbUsersHelper mDbHelper;

	private Cursor mCursor;

	private String mUserId;

	private boolean mViewLoadingHidden;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		SharedPreferences prefs = getActivity().getSharedPreferences(FBOAuthHelper.AUTH_PREFS, Context.MODE_PRIVATE);
		mUserId = prefs.getString(FBOAuthHelper.USER_ID, null);
		mProfileFeedAdapter = new FeedCursorAdapter(ContextHolder.getInstance().getContext(), null);
		LoaderManager loader = getLoaderManager();
		Bundle paramBundle = new Bundle();
		paramBundle.putString(FbConstants.USER_ID, mUserId);
		loader.initLoader(0, paramBundle, new LoaderCallbacks<Cursor>() {

			@Override
			public Loader<Cursor> onCreateLoader(int paramInt, Bundle paramBundle) {
				String where = FbContract.profileId(paramBundle.getString(FbConstants.USER_ID));
				return new CursorLoader(getActivity(), FbContract.FeedColumns.CONTENT_URI, null, where, null, null);
			}

			@Override
			public void onLoadFinished(Loader<Cursor> paramLoader, Cursor paramD) {
				mProfileFeedAdapter.swapCursor(paramD);
			}

			@Override
			public void onLoaderReset(Loader<Cursor> paramLoader) {
				mProfileFeedAdapter.swapCursor(null);
			}
		});
		mBroadcastReceiver = new BroadcastReceiver() {
			
			@Override
			public void onReceive(Context context, Intent intent) {
				String action = intent.getAction();
				if (action.equals(ProfileService.ACTION_ON_ERROR)) {
					hideViewRefreshing(true);
					Toast.makeText(getActivity(), intent.getStringExtra(ProfileService.EXTRA_KEY_MESSAGE),Toast.LENGTH_SHORT).show();
				} else if (action.equals(ProfileService.ACTION_ON_SUCCESS)) {
					Log.d(LOG_TAG,"ProfileService.ACTION_ON_SUCCESS");
					hideViewRefreshing(true);
					setProfileInfoValues();
				} else if(action.equals(FeedService.PROFILE_FEED_ON_SUCCESS)){
					mIsLoading = false;
					mNextPageUrl = intent.getStringExtra(FeedService.NEXT_PAGE);
					Log.d(LOG_TAG,"nextProfFeedUrl="+ mNextPageUrl );
					if(mNextPageUrl.equals(FeedService.NO_PAGES) || mNextPageUrl ==null) hideViewLoading(true);
				} else if(action.equals(FeedService.PROFILE_FEED_ON_ERROR)){
					mIsLoading=false;
					hideViewLoading(true);
				}
			}
		};
		IntentFilter filter = new IntentFilter();
		filter.addAction(FeedService.PROFILE_FEED_ON_ERROR);
		filter.addAction(FeedService.PROFILE_FEED_ON_SUCCESS);
		filter.addAction(ProfileService.ACTION_ON_ERROR);
		filter.addAction(ProfileService.ACTION_ON_SUCCESS);
		ContextHolder.getInstance().getContext().registerReceiver(mBroadcastReceiver, filter);
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		ContextHolder.getInstance().getContext().unregisterReceiver(mBroadcastReceiver);
	}

	@Override
	public void onResume() {
		mProfileFeedAdapter.notifyDataSetChanged();
		super.onResume();
		
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		View v = inflater.inflate(R.layout.fragment_profile_page, null);
		setRetainInstance(true);
		mIsLoading = false;
		mNextPageUrl = FeedService.NO_PAGES;
		mListViewProfile = (ListView) v.findViewById(android.R.id.list);
		mViewProfileInfo = inflater.inflate(R.layout.view_header_profile, null);
		mViewLoading = inflater.inflate(R.layout.view_listitem_loading, null);
		mViewRefreshish = inflater.inflate(R.layout.view_refreshig, null);
		mListViewProfile.addHeaderView(mViewProfileInfo);
		mListViewProfile.addHeaderView(mViewRefreshish);
		mListViewProfile.addFooterView(mViewLoading);
		hideViewRefreshing(true);
		hideViewLoading(true);
		setProfileInfoValues();
		mListViewProfile.setAdapter(mProfileFeedAdapter);
		mListViewProfile.setOnScrollListener(this);
		mButtonRefresh = (ImageButton) v.findViewById(R.id.btnRefresh);
		mButtonRefresh.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				if(!InetChecker.checkInetConnection(getActivity())){ return; }
				mIsLoading=true;
				hideViewRefreshing(false);
				Intent intent = new Intent(getActivity(), ProfileService.class);
				RequestBuilder requestBuilder = new RequestBuilder();
				requestBuilder.setType(RequestBuilder.Type.GET);
				requestBuilder.setUrl(ApiRequest.getUserSimple(mUserId)); 
				intent.putExtra(ProfileService.HTTP_REQUEST_BUILDER, requestBuilder);
				getActivity().startService(intent);
				DbNewsfeedHelper dbHelper = new DbNewsfeedHelper(getActivity().getApplicationContext(), null);
				dbHelper.deleteItem(FbContract.FeedColumns.TABLE_TYPE, FbContract.profileId(mUserId));
				dbHelper.close();
				String url = ApiRequest.getProfileFeedApiUrl(mUserId);
				url = ApiRequest.addToken(url);
				url=url+"&limit=8";
				loadFeedPage(url);
			}
		});
		mButtonAdd = (ImageButton) v.findViewById(R.id.btnNewPost);
		mButtonAdd.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				if(!InetChecker.checkInetConnection(getActivity())){
					return;
				}
				Intent post = new Intent(getActivity(), NewPostActivity.class);
				post.putExtra(FbConstants.ID, mUserId);
				startActivityForResult(post, 0);
			}
		});

		return v;
	}
	
	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		
	}

	void setProfileInfoValues() {
		mTextViewName = (TextView) mViewProfileInfo.findViewById(R.id.tvProfileName);
		mTextViewBirthDay = (TextView) mViewProfileInfo.findViewById(R.id.tvProfileAge);
		mTextViewLocation = (TextView) mViewProfileInfo.findViewById(R.id.tvProfileLocation);
		mImageView = (ImageView) mViewProfileInfo.findViewById(R.id.ivProfileImage);
		mDbHelper = new DbUsersHelper(this.getActivity(), null);
		mCursor = mDbHelper.getItems();
		 if (mCursor.moveToFirst()) {		        
			 Log.d("Proffragm.setvals", mUserId);
		        do {
		        	if(mCursor.getString(mCursor.getColumnIndex(FbContract.UserProfileColumns.ITEM_ID)).equals(mUserId)){
			    		mTextViewName.setText(mCursor.getString(mCursor.getColumnIndex(FbContract.UserProfileColumns.NAME)));
			    		mTextViewBirthDay.setText(mCursor.getString(mCursor.getColumnIndex(FbContract.UserProfileColumns.BIRTHDAY)));
			    		mTextViewLocation.setText(mCursor.getString(mCursor.getColumnIndex(FbContract.UserProfileColumns.LOCATION)));
			    		ImageLoader imLoader = ImageLoader.getInstance();
			    		mImageView.setImageBitmap(null);
			    		imLoader.bind(mImageView, mCursor.getString(mCursor.getColumnIndex(FbContract.UserProfileColumns.PICTURE_URL)));
			    		mDbHelper.close();
			    		return;
		        	}
		        } while (mCursor.moveToNext());
		 }
	}

	@Override
	public void onListItemClick(ListView l, View v, int position, long id) {
		InetChecker.checkInetConnection(getActivity());
		try{
			Cursor cursor = (Cursor) l.getItemAtPosition(position);
			Intent intent = new Intent(this.getActivity(), FeedItemActivity.class);
			intent.putExtra(FbConstants.ITEM_ID, cursor.getString(cursor.getColumnIndex(FbContract.FeedColumns.ITEM_ID)));
			intent.putExtra(FbConstants.USER_ID, cursor.getString(cursor.getColumnIndex(FbContract.FeedColumns.FROM_ID)));
			intent.putExtra(FbConstants.FEED_TYPE, cursor.getString(cursor.getColumnIndex(FbContract.FeedColumns.TABLE_TYPE)));
			startActivity(intent);
		}
		catch(Exception e){
			Log.e(LOG_TAG, e.toString());
		}
	}

	@Override
	public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
		if (visibleItemCount > 0 && firstVisibleItem + visibleItemCount + 3 >= totalItemCount && !mNextPageUrl.equals(FeedService.NO_PAGES)) {
			if(!mIsLoading){
				mIsLoading = true;
				if(mViewLoadingHidden) hideViewLoading(false);
				loadFeedPage(mNextPageUrl);
			}
		}
	}

	@Override
	public void onScrollStateChanged(AbsListView absListView, int i) {}

	public void loadFeedPage(String url) {
		Intent intent = new Intent(getActivity(), FeedService.class);
		RequestBuilder requestBuilder = new RequestBuilder();
		requestBuilder.setType(RequestBuilder.Type.GET);
		requestBuilder.setUrl(url);
		requestBuilder.setDbMarker(FbContract.profileId(mUserId));
		intent.putExtra(FeedService.HTTP_REQUEST_BUILDER, requestBuilder);
		getActivity().startService(intent);
	}

	private void hideViewRefreshing(boolean hide){
		ViewHider.hideListItem(mViewRefreshish, hide);
	}

	private void hideViewLoading(boolean hide){
		mViewLoadingHidden=hide;
		ViewHider.hideListItem(mViewLoading, hide);
	}

}
